# -*- coding: UTF-8 -*-
import kivy

from kivy.uix.button import Button
from kivy.properties import BooleanProperty, StringProperty, NumericProperty,\
    ListProperty
from ui.disableable_button import DisableableButton

from kivy.clock import Clock


class ConfirmationButton(DisableableButton):
    text_normal = StringProperty()
    color_normal = StringProperty('default')
    text_confirm = StringProperty()
    color_confirm = StringProperty('red')
    time = 1
    time_to_confirm_sec = NumericProperty(1)
    is_confirming = BooleanProperty(False)
    is_always_normal_button = False
    is_normal_button = BooleanProperty(False)

    __events__ = ('on_confirm',)

    def __init__(self, **kwargs):
        self.text_confirm = _('Confirm')
        self.time_to_confirm_sec = float(ConfirmationButton.time) / 10
        if self.time_to_confirm_sec <= 0:
            self.is_always_normal_button = True
        super(ConfirmationButton, self).__init__(**kwargs)
        self.bind(text_normal=self._update,
                  text_confirm=self._update,
                  is_confirming=self._update)
        self.register_event_type('on_confirm')

    def _update(self, *args):
        if self.is_confirming:
            self.text = self.text_confirm
            self.color_name = self.color_confirm
        else:
            self.text = self.text_normal
            self.color_name = self.color_normal

    def on_release(self):
        if self.is_always_normal_button or self.is_normal_button:
            self.dispatch('on_confirm')
            return
        if not self.is_confirming:
            self.is_confirming = True
            Clock.schedule_once(self._on_timer, self.time_to_confirm_sec)
        else:
            self.is_confirming = False
            self.dispatch('on_confirm')

    def _on_timer(self, dt):
        self.is_confirming = False

    def on_confirm(self):
        pass
